package com.factory.aiclient.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.factory.aiclient.manager.SocketManager;
import com.factory.aiclient.manager.WebRTCManager;
import com.factory.aiclient.service.LocationService;
import com.factory.aiclient.service.UserDeviceService;
import com.factory.aiclient.service.UserService;
import com.factory.aiclient.util.SpringCtxUtils;
import com.factory.common.bean.Location;
import com.factory.common.bean.User;
import com.factory.common.bean.UserDevices;
import com.factory.common.constant.DeviceConstant;
import com.factory.common.pojo.Result;
import com.factory.common.pojo.SendData;
import com.factory.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/aiclient/index")
@Slf4j
@CrossOrigin
public class IndexController {

    @Autowired
    private UserDeviceService userDeviceService;

    @Autowired
    private UserService userService;

    @Autowired
    private LocationService locationService;

    /**
     * 设备注册接口
     *
     * @param param
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody Map<String, Object> param) {
        log.info("设备注册接口,{}", param);

        if (StringUtil.isEmpty(param.get("name"))) {
            return Result.fail("设备名称不能为空");
        } else if (StringUtil.isEmpty(param.get("model"))) {
            return Result.fail("设备型号不能为空");
        } else if (StringUtil.isEmpty(param.get("version"))) {
            return Result.fail("版本号不能为空");
        }

        String id = StringUtil.randomStr2(9);

        Integer count = userDeviceService.selectCount(new QueryWrapper<UserDevices>().eq("id", id));
        if(null != count && count > 0 ){
            id = StringUtil.randomStr2(9);
        }

        UserDevices current = new UserDevices();
        current.setId(id);
        current.setName(param.get("name").toString());
        current.setImage("");
        current.setModel(param.get("model").toString());
        current.setVersion(param.get("version").toString());
        current.setStatus(DeviceConstant.Status.INVALID);
        current.setCreateDate(new Date());

        userDeviceService.insert(current);

        return Result.success(current, "设备注册成功!");
    }

    /**
     * 添加位置信息
     * @param param
     * @return
     */
    @PostMapping("/insertLocation")
    public Result insertLocation(@RequestBody Map<String,Object> param){
        log.info("添加位置信息,{}",param);
        if(StringUtil.isEmpty(param.get("name"))){
            return Result.fail("名称不能为空!");
        }

        if (StringUtil.isEmpty(param.get("username")))
            return Result.fail("请输入用户名");
        else if (StringUtil.isEmpty(param.get("password")))
            return Result.fail("请输入密码");

        User user = userService.getByAccount(param.get("username").toString());
        if (null == user)
            return Result.fail("用户不存在");
        else if (!user.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(param.get("password").toString().getBytes())))
            return Result.fail("输入密码不正确");

        Location location = new Location();
        location.setId(StringUtil.getUUID());
        location.setCreateDate(new Date());
        location.setName(param.get("name").toString());
        location.setUserId(user.getId());
        location.setUserName(user.getName());
        location.setAddress(StringUtil.val(param.get("address"),""));

        locationService.insert(location);

        return Result.success(location,"添加成功!");
    }

    /**
     * 查询位置信息列表
     * @param param
     * @return
     */
    @PostMapping("/locations")
    public Result locations(@RequestBody Map<String,Object> param){
        log.info("查询位置信息列表,{}",param);

        QueryWrapper<Location> locationQueryWrapper = new QueryWrapper<>();
        locationQueryWrapper.ge("status",0);

        if(StringUtil.notEmpty(param.get("username"))){
            User user = userService.getByAccount(param.get("username").toString());

            if (null != user)
                locationQueryWrapper.eq("user_id",user.getId());
        }

        return Result.success(locationService.selectList(locationQueryWrapper),"添加成功!");
    }

    /**
     * 获取在线的设备列表
     * @param jsonObject
     * @return
     */
    @RequestMapping("/onLines")
    public Result onLines(@RequestBody JSONObject jsonObject){
        return Result.success(SocketManager.getOnLines(jsonObject.getString("userId")));
    }

    /**
     * 检查设备是否在线
     * @param deviceId
     * @return
     */
    @RequestMapping("/isOnLine/{deviceId}")
    public Result isOnLine(@PathVariable String deviceId){
        return Result.success(SocketManager.isOnLine(deviceId));
    }

    /**
     * 发送到客户端数据
     * @return
     */
    @RequestMapping(value = "/sendClient", method = RequestMethod.POST)
    public Result sendClient(@RequestBody SendData sendData){
        log.info("发送到客户端数据,{}", sendData);

        if(StringUtil.isEmpty(sendData.getId()))
            return Result.fail("ID不能为空!");
        else if("execute".equals(sendData.getMethod()))
            return Result.success(SpringCtxUtils.execute(StringUtil.val(sendData.getData(),"")));
        else if(!SocketManager.isOnLine(sendData.getId()))
            return Result.fail("设备不在线，发送失败");

        if(sendData.getSync())
            return SocketManager.sendSyncMessage(sendData.getId(), sendData);
        else
            SocketManager.sendMessage(sendData.getId(), sendData);

        return Result.success(null);
    }

    /**
     * 发送webrtc信令数据
     * @param jsonObject
     * @return
     */
    @PostMapping("/webRtc")
    public Result webRtc(@RequestBody JSONObject jsonObject){
        log.info("发送到webRtc客户端数据");

        if(!jsonObject.containsKey("toUserId")){
            return Result.fail("toUserId not null");
        }

        WebRTCManager.sendMessage(jsonObject.getString("toUserId"), jsonObject.toJSONString());

        return Result.success(null);
    }
}
